package com.tan.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tan.exception.BusinessException;
import com.tan.jwt.JWTToken;
import com.tan.mapper.UserMapper;
import com.tan.pojo.Menu;
import com.tan.pojo.Role;
import com.tan.pojo.User;
import com.tan.pojo.vo.UserInnerDepartmentVO;
import com.tan.response.ResultCode;
import com.tan.service.IUserService;
import com.tan.utils.JWTUtils;
import com.tan.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author tanRuYi
 * @since 2021-08-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    MenuServiceImpl menuService;

    @Override
    public Page<UserInnerDepartmentVO> getUserByUserByPage(UserInnerDepartmentVO user, Page page){

        return this.baseMapper.getUserByUserByPage(user, page);
    }

    /**
     * 导出用户Excel
     *
     */
    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> users) throws IOException {
        //----- 写入excel文件

        String exportFileName = "TbUserInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(users);
    }

    /**
     * 根据用户名和密码去实现登录
     */
    @Override
    public String login(String username, String password) {
        String token = "";
        //先要根据用户名查询用户信息
        User user = this.baseMapper.findUserByName(username);
        if(user!=null){
            //如果存在则要生成token
            //1.先获取用户的盐
            String salt = user.getSalt();
            //2.对原始密码进行加密加盐操作
            String md5Password = MD5Utils.md5Encryption(password, salt);
            if(md5Password.equals(user.getPassword())){
                //3.要生成token
                token = JWTUtils.sign(user.getUsername(), md5Password);

                JWTToken jwtToken = new JWTToken(token);
                try {
                    SecurityUtils.getSubject().login(jwtToken);
                } catch (AuthenticationException e) {
                    //打印异常信息到控制台
                    e.printStackTrace();
                    throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST);
                }
            }else{
                throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR);
            }
        }else{
            //用户不存在则直接抛出异常
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        return token;
    }

    @Override
    public User findUserByName(String username) {
        return this.baseMapper.findUserByName(username);
    }

    /**
     * 根据用户的id查询角色的列表
     */
    @Override
    public List<Role> findRolesById(Long id) {
        User user = this.baseMapper.selectById(id);
        if(user==null){
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        return this.baseMapper.findRolesById(id);
    }

    /**
     * 查询登录用户具有的菜单(包含了权限和按钮)
     */
    @Override
    public List<Menu> findMenuByRoles(List<Role> roles) {
        List<Menu> menus = new ArrayList<>();
        //定义一个菜单id的集合
        Set<Long> menuIds = new HashSet<>();
        for (Role role : roles) {
            //获取角色的id,根据角色id查询菜单id
            List<Menu> menuList = menuService.getBaseMapper().getMenuListByRoleId(role.getId());
            //去重拼接
            for (Menu menu: menuList) {
                menuIds.add(menu.getId());
            }
        }

        //根据所有的菜单ID查询菜单
        //循环所有的菜单id
        for (Long menuId: menuIds) {
            Menu menu = menuService.getMenuByMenuId(menuId);
            menus.add(menu);
        }

        return menus;
    }
}
